package cn.cai.handler;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 403访问受限错误解决处理器
 * 当访问发生403错误的时候，SpringSecurity自动调用。
 * SpringSecurity想调用类中的方法，处理403错误，必须能在Spring容器中获取对象
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 处理403错误的真实方法
     * @param httpServletRequest  请求对象
     * @param httpServletResponse 响应对象
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        // 设置响应状态
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        // 设置响应类型
        httpServletResponse.setContentType("text/html; charset=UTF-8");
        // 响应输出
        httpServletResponse.getWriter().println("<html><body><div style='width:800px;text-align:center;margin:auto;font-size:24px'>权限不足，请联系管理员</div></body></html>");
        // 刷新输出流的缓冲区
        httpServletResponse.getWriter().flush();

    }
}
